package com.qys.livesMall.shop.controller.app;

/**
 * @packageName:
 * @className:ShopCartController
 * @Description:
 * @author:guomx
 * @date:2023/6/1910:45
 */

import com.qys.livesMall.common.result.R;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.modal.dto.ShopCartDto;
import com.qys.livesMall.shop.modal.dto.ShopCartInfo;
import com.qys.livesMall.shop.modal.entity.ShopCart;
import com.qys.livesMall.shop.service.ShopCartService;
import jakarta.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/app/cart")
public class ShopCartController {

    @Resource
    private ShopCartService cartService;


    /****
     * 购物车列表
     * @return
     */
    @GetMapping(value = "/list")
    public R<List<ShopCartInfo>> list(){
        Long userId = SecurityUtils.getUserId();
        List<ShopCart> carts = cartService.list(userId);
        if (CollectionUtils.isEmpty(carts)){
            return R.ok();
        }
        Map<Long,List<ShopCart>> maps=carts.stream().collect(Collectors.groupingBy(ShopCart::getShopId));
        List<ShopCartInfo> cartInfos=new ArrayList<>();
        for (Long shopId:maps.keySet()){
            ShopCartInfo info=new ShopCartInfo();
            info.setShopId(shopId);
            info.setShopName(maps.get(shopId).get(0).getShopName());
            info.setShopCarts(maps.get(shopId));
            cartInfos.add(info);
        }
        return R.ok(cartInfos);
    }

    /***
     * 添加购物车
     * id: skuid
     */
    @PostMapping(value = "/add")
    public R add(@RequestBody ShopCartDto cartDto){
        //用户名字
        Long userId = SecurityUtils.getUserId();
        String userName= SecurityUtils.getUsername();
        //加入购物车
        return cartService.add(cartDto,userId,userName);
    }

    /***
     * 删除指定购物车
     */
    @DeleteMapping
    public R delete(@RequestBody List<String> ids){
        //删除购物车集合
        return cartService.delete(ids);
    }

}
